<?php
/**
 * Created by PhpStorm.
 * User: xiaotao
 * Date: 18-5-3
 * Time: 下午5:20
 *
 */

namespace app\manage\controller;
use app\common\model\Menu as MenuM;
use app\common\validate\Menu as MenuV;
use think\Request;

class Menu  extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = MenuM::select();
        $count = count($list);
        $data = [
            'items' => $list ?: [],
            'total' => $count
        ];
        return $this->result_json(null, 1, $data);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $request->only(['name', 'link', 'param', 'icon', 'is_other', 'is_blank', 'type', 'sort', 'status']);
        $validate = new MenuV();
        if (!$validate->scene('New')->check($data)) {
            return $this->result_json($validate->getError(), 201);
        }
        $instance = new MenuM();
        if ($instance->save($data)) {
            return $this->result_json('create success', 1, ['id' => $instance->id]);
        } else {
            return $this->result_json('db error', 101);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {

    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        // 字段验证和合法性验证
        $data = $request->only(['name', 'link', 'param', 'icon', 'is_other', 'is_blank', 'type', 'sort', 'status']);
        $validate = new MenuV();
        if (!$validate->scene('Update')->check($data)) {
            return $this->result_json($validate->getError(), 201);
        }

        $instance = MenuM::get($id);    // 是否只查询单个字段
        if ($instance) {
            if ($instance->save($data) === false) {
                return $this->result_json('db error', 101);
            }
            return $this->result_json('update success', 1);
        } else {
            return $this->result_json('param error', 201);
        }
    }


    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id, $flag = 'true')
    {
        $instance = MenuM::where('id', $id)->find();
        if (!$instance) {
            return $this->result_json('param error', 201);
        }

        $instance->status = $flag === 'true' ? -1 : 1;
        // 执行删除操作
        if ($instance->save() === false) {
            return $this->result_json('param error', 201);
        }
        return $this->result_json('delete success', 0);
    }


}